package com.huluobo.base.mvvm

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.ViewModelProvider
import com.blankj.utilcode.util.TimeUtils
import com.blankj.utilcode.util.ToastUtils
import java.lang.reflect.ParameterizedType
import java.text.SimpleDateFormat

/**
 *  Created by LC on 2024/7/24.
 */
abstract class BaseActivity<VDB : ViewDataBinding, VM : BaseViewModel> : AppCompatActivity() {
    //首先拿到class的type 是一个activity还是viewmodel
    private val type by lazy { (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments }
    protected val binding: VDB by lazy {
        //如果是一个Activity view的类型
        val clazz = type[0] as Class<VDB>
        //拿到它导入布局的方法
        val method = clazz.getMethod("inflate", LayoutInflater::class.java)
        //再将VDB导入到当前activity的布局
        method.invoke(null, layoutInflater) as VDB
    }

    protected val viewModel: VM by lazy {
        val clazz = type[1] as Class<VM>
        ViewModelProvider(this)[clazz]
    }

    open fun onError(t: Throwable) {
        ToastUtils.showLong(t.message)
        Log.i("TagA", "t:${t.message}")
        t.printStackTrace()//自己抛出异常报错
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        viewModel.onFailed.observe(this, ::onError)
        initView()
        initData()
    }

    //重写home键方法,单击home键时,关闭掉当前activity
    override fun onOptionsItemSelected(item: MenuItem) =
        when (item.itemId) {
            android.R.id.home -> {
                finish()
                true
            }

            else -> super.onOptionsItemSelected(item)
        }


    abstract fun initData()

    abstract fun initView()

    fun getTime(): String {
        val time = System.currentTimeMillis();
        var tampTIme = TimeUtils.millis2String(time, SimpleDateFormat("yyyy-MM-dd"))
        tampTIme += "T"
        tampTIme = tampTIme + TimeUtils.millis2String(time, SimpleDateFormat("hh:mm:ss"))
        tampTIme += "Z"
        return tampTIme
    }
}